#include "task_app_logic.h"

static TaskHandle_t thread_app;

u8 app_logic_init()
{
  pack_regiser_data(); //首次上电的时候上报注册包
  app_logic_set_front_last_ssp(SSP_LOGO);
  app_logic_set_front_ssp(SSP_POWER_OFF);
  app_logic_set_around_last_ssp(SSP_LOGO);
  app_logic_set_around_ssp(SSP_POWER_OFF);
  app_logic_set_corner_last_ssp(SSP_LOGO);
  app_logic_set_corner_ssp(SSP_POWER_OFF);
  
  state_num = STATE_COMMON;
  cnt =0;
  return 1;
}

SYS_OPT_KEY app_logic_act_to_opt(key_act_param key_act)
{
    SYS_OPT_KEY opt;
    if(key_act.drvAct == DRV_ACT_NONE)
    {
      opt.oepation = OPT_NONE;
      opt.target = 0; //随便写一个
    }
    

    switch (key_act.key_num)
    {
      case 0: //前灯带开关
        opt = front_on_off_opt(key_act.drvAct);
        break;

      case 1: //前灯带模式
        opt = front_mode_opt(key_act.drvAct);
        break;

      case 2: //左右灯带开关
        opt = around_on_off_opt(key_act.drvAct);
        break;

      case 3: //左右灯带模式
        opt = around_mode_opt(key_act.drvAct);
        break;
      
      case 4: //三角灯开关及模式
        opt = corner_mode_on_off_opt(key_act.drvAct);
      break;

      default:
        
        break;
    }
    LOG_INFO("opt.oepation is %d,opt.target is %d\n",opt.oepation,opt.target);
    return opt;
}


void app_logic_general_handle(SYS_OPT_KEY opt)
{
    mode_front_handle(opt);
    mode_around_handle(opt);
    mode_corner_handle(opt);
}

void app_logic_loop(void *pvParameters)
{
  key_act_param key_act; //
  SYS_OPT_KEY opt;
  app_logic_init();

  while(1)
  {
    opt.oepation = OPT_NONE;
    opt.target = 0; //随便写的
    if(xQueueReceive(sensor_dect_queue,&key_act,0))
    {
        LOG_INFO("app logic task : recv msg,type is %d,key num is %d\n",key_act.drvAct,key_act.key_num); //接收到按键操作动作
        opt=app_logic_act_to_opt(key_act);
    }
    
    if(state_num == STATE_COMMON) //在普通模式下 没啥特殊操作
    {
      app_logic_general_handle(opt);
    }
    else
    {
      cnt++;

      if (cnt>500) //超过5s没连接
      {
        if(state_num == STATE_OTA)
        {
            esp_restart();
        }
        else if(state_num == STATE_PLAY)
        {
            app_logic_set_front_last_ssp(SSP_LOGO);
            app_logic_set_around_last_ssp(SSP_LOGO);
            app_logic_set_corner_last_ssp(SSP_LOGO);
            state_num = STATE_COMMON;
            pack_uart_quit_data(); //主动被动上报都放这里
        }
         printf("cnt = %d\n",cnt);
      }
    }
    vTaskDelay(pdMS_TO_TICKS(EXAMPLE_CHASE_SPEED_MS)); //延时10ms
  }
}


void task_app_logic_init()
{
    xTaskCreate(app_logic_loop,"app_logic_loop",7168,NULL,TASK_PROP_APP,&thread_app);
}